#include "login.h"
#include "ui_login.h"
#include"homepage.h"

login::login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);


    socket = new QTcpSocket(this);
    connect(ui->pushButtonRegister,SIGNAL(clicked()),this,SLOT(signalSLots()));
    connect(ui->pushButtonLogin,SIGNAL(clicked()),this,SLOT(signalSLots()));

    socket->connectToHost("192.168.51.62",9966);


    //连接提示
    connect(socket,SIGNAL(connected()),this,SLOT(connectedSlot()));
    //断提示
    connect(socket,SIGNAL(disconnected()),this,SLOT(disconnectedSlot()));
    //收到"0 1"进行登录
    connect(socket,SIGNAL(readyRead()),this,SLOT(readSLOT()));


}

login::~login()
{
    delete ui;
}

void login::signalSLots()
{
    if(sender()==ui->pushButtonRegister)
    {
        if(ui->labelLoginStatus->text()=="登录界面")
        {
            QMessageBox::information(this,"提示","开始注册");
            ui->pushButtonLogin->setEnabled(false);
            ui->labelLoginStatus->setText("注册界面");
        }
        else if(ui->labelLoginStatus->text()=="注册界面")
        {
            if(ui->lineEditAccount->text()==""||ui->lineEditPassword->text()=="")
            {
                QMessageBox::information(this,"提示","注册失败请输入账号或密码");
                return ;
            }
            QMessageBox::information(this,"提示","注册成功");
            ui->pushButtonLogin->setEnabled(true);
            ui->labelLoginStatus->setText("登录界面");
            //账号密码存入数据库
            QString text;
            text.append(ui->lineEditAccount->text()).append("/").append(ui->lineEditPassword->text()).prepend("0/");
            QByteArray buffer = text.toUtf8();
            // 发送
            socket->write(buffer);
            ui->lineEditAccount->clear();
            ui->lineEditPassword->clear();
        }

    }
    else if(sender()==ui->pushButtonLogin)
    {
        ui->labelLoginStatus->setText("登录界面");
        //账号密码存入数据库
        QString text;
//        text.append(ui->lineEditAccount->text()).append("/").append(ui->lineEditPassword->text()).append("/").append("1");
        text.append(ui->lineEditAccount->text()).append("/").append(ui->lineEditPassword->text()).prepend("1/");
        QByteArray buffer = text.toUtf8();
        // 发送
        socket->write(buffer);


    }
    else
    {}

}

void login::connectedSlot()
{

  QMessageBox::information(this,"提示","连接成功");

}

void login::disconnectedSlot()
{
    QMessageBox::information(this,"提示","断开连接");
}

void login::readSLOT()
{
    QByteArray buffer = socket->readAll();
    // QByteArray → QString
    QString text(buffer);

    if(text=="1")
    {
        HomePage *h=new HomePage;
        h->show();
        close();
        QMessageBox::information(this,"提示","登录成功");


    }else if(text=="0")
    {

        QMessageBox::warning(this,"警告","账号或密码输入错误，请重新输入");
    }

}
